#include "Scene/RenderManager.h"

#include "GfxDriver/GfxDriver.h"
#include "Scene/RenderQueue.h"

namespace Orca {

	//--------------------------------------------------------------------------
	RenderManager::RenderManager(GfxDriver *gfxDriver) {

	}

	//--------------------------------------------------------------------------
	RenderManager::~RenderManager() {

	}

	//--------------------------------------------------------------------------
	void RenderManager::render(uint16 startQueueId, uint16 stopQueueId) {

		const uint32 cnt = (uint32)mRQList.size();

		uint32 startIdx, stopIdx;

		for(uint32 i = 0; i < cnt; ++i) {

			RenderQueue *rq = mRQList[i];

			stopIdx = i;

			if(rq->getId() <= startQueueId) startIdx = i;
			if(rq->getId() > stopQueueId) break;
		}

		for(uint32 i = startIdx; i < stopIdx; ++i)
			mRQList[i]->render(mGfxDriver);
	}

	//--------------------------------------------------------------------------
	void RenderManager::registerRenderQueue(
		  uint16 id
		, IRenderQueueSorter *sorter) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter != mRQMapping.end() )
			return;

		mRQMapping[id] = new RenderQueue(id, sorter);

		_refreshRQList();
	}

	//--------------------------------------------------------------------------
	void RenderManager::unregisterRenderQueue(uint16 id) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter == mRQMapping.end() )
			return;

		delete iter->second;
		mRQMapping.erase(iter);

		_refreshRQList();
	}

	//--------------------------------------------------------------------------
	RenderQueue* RenderManager::getRenderQueue(uint16 id) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter == mRQMapping.end() )
			return NULL;

		return iter->second;
	}

	//--------------------------------------------------------------------------
	void RenderManager::_refreshRQList() {

		mRQList.clear();

		TRQMapping::iterator curr = mRQMapping.begin();
		const TRQMapping::iterator end = mRQMapping.end();

		while(curr != end) {

			mRQList.push_back(curr->second);
			++curr;
		}
	}

	//--------------------------------------------------------------------------
}